const http=require("http");
const mysql =require("mysql");

const conn=mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"123456",
    database:"bookshop"
})

const server=http.createServer((req,res)=>{
    // 解决中文乱码
    res.setHeader("content-type","application/json;charset=utf8")
    req.path=req.url.split("?")[0];

    switch(req.path){
        case "/":
            let data={
                msg:"请求根目录",
            }
            res.end(JSON.stringify(data))
            break;
        case "/login":
            //const users = [ { username: 'admin', password: 'password123' } ];
            // 获取参数
            let url="http://localhost:8080"+req.url;
            let myURL=new URL(url);
            let username=myURL.searchParams.get("username");
            let password=myURL.searchParams.get("password");
            // 判断用户是否存在
            //let flag=false;
            // users.forEach(user=>{
            //     if(user.password===password&& user.username===username){
            //         flag=true;
            //     }
            // })
            // 数据库查询用户
            let sql=`select * from userinfo where username=? and password=?`;
            conn.query(sql,[username,password],(err,result)=>{
                if(err) throw err;
                if(result.length>0){
                    let data={
                        msg:"登录成功",
                        code:200,
                        username:username
                    }
                    res.end(JSON.stringify(data));
                }else{
                    let data={
                        msg:"登录失败",
                        code:401
                    }
                    res.end(JSON.stringify(data));
                }
            })

            // if(flag==true){
            //     let data={
            //         msg:"登录成功",
            //         code:200,
            //         username:username
            //     }
            //     res.end(JSON.stringify(data));
            // }else{
            //     let data={
            //         msg:"登录失败",
            //         code:401
            //     }
            //     res.end(JSON.stringify(data));
            // }
            break;
        default:
            break;
    }
})

server.listen(9000,()=>{
    console.log("启动后端服务。。。")
})